<template>
  <div class="download-topic-page">
    <el-card class="download-card">
      <div class="title">下载竞赛题目</div>
      <el-form label-width="100px">
        <el-form-item label="选择竞赛">
          <ContestSelector v-model="contestId" @change="onContestChange" />
        </el-form-item>
        <el-form-item label="选择题目" v-if="contestId">
          <TopicSelector :contestId="contestId" @change="onTopicChange" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :disabled="!topicId" @click="downloadTopic">下载题目文件</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import ContestSelector from '@/components/ContestSelector.vue'
import TopicSelector from '@/components/TopicSelector.vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'

const contestId = ref('')
const topicId = ref('')
const topicObj = ref(null)

const onContestChange = () => {
  topicId.value = ''
  topicObj.value = null
}
const onTopicChange = (topic) => {
  topicId.value = topic?.id || ''
  topicObj.value = topic
}

const downloadTopic = async () => {
  if (!contestId.value || !topicId.value) return
  try {
    const token = localStorage.getItem('token')
    const url = `/api/students/contests/${contestId.value}/topics/download?topicId=${topicId.value}`
    const res = await axios.get(url, {
      responseType: 'blob',
      headers: { 'Authorization': `Bearer ${token}` }
    })
    // 获取文件名
    let filename = `${topicObj.value?.name || '题目'}_${contestId.value}.pdf`
    const disposition = res.headers['content-disposition']
    if (disposition) {
      const match = disposition.match(/filename="(.+)"/)
      if (match) filename = decodeURIComponent(match[1])
    }
    // 下载文件
    const blob = new Blob([res.data], { type: 'application/pdf' })
    const link = document.createElement('a')
    link.href = window.URL.createObjectURL(blob)
    link.download = filename
    link.click()
    window.URL.revokeObjectURL(link.href)
    ElMessage.success('题目下载成功')
  } catch (e) {
    ElMessage.error('下载失败，请重试')
  }
}
</script>

<style scoped>
.download-topic-page {
  max-width: 600px;
  margin: 40px auto;
}
.download-card {
  padding: 32px 32px 24px 32px;
  border-radius: 10px;
  box-shadow: 0 2px 16px 0 rgba(60,90,150,0.08);
}
.title {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 24px;
  letter-spacing: 2px;
  color: #2d3a4b;
}
</style>
